/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************
 * MIFSS  - content storage system
 * 
 *
 * @uthors: uros.kristan@gmail.com (Uroš Kristan ) Urosk.NET
 *         jernej.svigelj@gmail.com (Jernej Švigelj) 
 */
package net.monare.mifss.managers;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import net.monare.mifss.configurations.pojo.StorageDef;
import net.monare.mifss.exceptions.MediaConverterException;
import net.monare.mifss.exceptions.TransformationHandlerException;
import net.monare.mifss.exceptions.TransformationManagerException;
import net.monare.mifss.lib.AppContext;
import net.monare.mifss.workers.BaseTransformationHandler;
import net.monare.mifss.workers.interfaces.FileHandler;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TransformationManager {

	@Autowired
	private FileHandler fileHandler;

	private static final Logger logger = Logger.getLogger(TransformationManager.class);

	public BaseTransformationHandler getTransformationHandlerImplementation(String transformationHandlerName) throws TransformationManagerException {

		BaseTransformationHandler transformationHandler = null;
		try {
			// get pool implementation bean from its name
			transformationHandler = (BaseTransformationHandler) AppContext.getApplicationContext().getBean(transformationHandlerName);

		} catch (BeansException be) {

			String errMessage = "Can not find transformation definiton for transformationHandlerName " + transformationHandlerName;
			logger.error(errMessage, be);
			throw new TransformationManagerException(errMessage);

		}

		return transformationHandler;

	}

	public File transform(final StorageDef storageDef, final File inputFile) throws TransformationManagerException {

		String transformationHandlerName = storageDef.getTransformationHandlerName();

		BaseTransformationHandler th = getTransformationHandlerImplementation(transformationHandlerName);
        th.setStorageDef(storageDef);



        if (logger.isDebugEnabled()) {

			logger.info("passed file : " + inputFile.getAbsolutePath() + " to transformation Manager..");
			logger.debug(transformationHandlerName);
		}

		try {

            // initialize handler
            th.initialize();

			File outputFile = null;
			String mimeType = fileHandler.getMimeType(inputFile);

			// if mime type supported then convert it
			if (th.isMimeTypeSupported(mimeType)) {

				String ext = th.getPropertyString("result_extension");
				outputFile = File.createTempFile(UUID.randomUUID().toString(), "." + ext);

				if (logger.isDebugEnabled()) {
					logger.debug("transforming " + inputFile.getAbsolutePath() + " to " + outputFile.getAbsolutePath());
				}

				th.transform(mimeType, inputFile, outputFile);

			} else {
				logger.warn("Mime type " + mimeType + " is not supported for this transformation handler ! file:   " + inputFile);
			}

			return outputFile;

		} catch (TransformationHandlerException | IOException | MediaConverterException e) {

			String errMessage = "Transformation of the content " + inputFile.getAbsolutePath() + " failed. Reason for failure: " + e.getMessage();
			logger.error(errMessage, e);
			throw new TransformationManagerException(errMessage, e);
		}

	}
}
